<?php
	/**
	 * Created by PhpStorm.
	 * User: mybook-lhp
	 * Date: 18/7/3
	 * Time: 下午3:55
	 */

	namespace app\common\behavior;


	use app\common\traits\apiinit;
	use app\common\utils\UtilJwt;

	class Auth
	{
		use apiinit;

		/**
		 * @param $params
		 * @throws \think\Exception
		 */
		public function run(&$params)
		{
			if ((defined('ENTRANCE') && ENTRANCE == 'api') || request()->module() == 'api' || strpos(request()->baseFile(), 'api.php') !== false)
			{
				$this->token();
			}
		}

		/**
		 * @throws \think\Exception
		 */
		protected function token()
		{

			//$url = request()->module() . '/' . request()->controller() . '/' . request()->action();
			$url = substr(str_replace('_', '', $_SERVER['PATH_INFO']), 1);

			$api_ignore_path = config('api_ignore_path');
			foreach ($api_ignore_path as &$item)
			{
				$item = str_replace('_', '', trim(strtolower($item)));
 			}
			unset($item);

			if (!in_array(strtolower($url), $api_ignore_path))
			{
				if (isset($_SERVER['HTTP_X_AUTH_TOKEN']) && $jwt = UtilJwt::decode($_SERVER['HTTP_X_AUTH_TOKEN'], config('JwtKey')))
				{
					define('HTTP_X_AUTH_TOKEN', $jwt);
				} else
				{
					$this->result([], 500, "Token不存在！或者Token验证失败！...", 'json');
				}
			}
		}
	}